/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.corticon.dialogs.validation;

import java.util.ArrayList;
import java.util.List;

import org.springframework.validation.Errors;

import com.corticon.dialogs.model.User;

/**
 *
 * @author Yanglifan
 */
public abstract class UserValidator<T> extends GenericHibernateValidator {

    @Override
    public void complexValidate(Object object, Errors errors) {
        User user = (User) object;
        passwordValidate(user, errors);
    }

    // ********** Inner Methods ********** //
    protected void passwordValidate(User user, Errors errors) {

        // Validate whether the two passwords are same.
        if (user.getPassword() != null && !user.getPassword().equals(user.getConfirmPassword())) {
            errors.rejectValue("confirmPassword", "validate.user.confirmPassword",
                "The passwords entered do not match.");
        }

        boolean isValidPassword = false;

        // Check that whether the password has the characters must be involved in.
        isValidPassword =
            checkValidCharacters(user.getPassword(), '0', '9', null) && (checkValidCharacters(user.
            getPassword(), 'a', 'z', null) || checkValidCharacters(user.getPassword(),
            'A', 'Z', null));

        // Declare the characters can not to be involved in.
        List<Character> excludedChars = new ArrayList<Character>();
        excludedChars.add('-');
        excludedChars.add('_');

        // Check that whether the password has the characters can not to be involved in.
        if (isValidPassword) {
            isValidPassword = checkInvalidCharacters(user.getPassword(), ' ', '/',
                excludedChars) && checkInvalidCharacters(user.getPassword(), ':', '@',
                excludedChars) && checkInvalidCharacters(user.getPassword(), '[', '`',
                excludedChars) && checkInvalidCharacters(user.getPassword(), '{', '~',
                excludedChars);
        }

        // If the password is invalid, add the error message.
        if (!isValidPassword) {
            errors.rejectValue("password", "validate.user.password.invalid",
                "The password must consist of at least 1 alpah and at least 1 numeric characters.");
        }
    }
}
